package com.dimbottom.util;

import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.List;

public class Connection {

    CloseableHttpClient client;

    /**
     * 根据 {@param URL} 和 {@param Headers} 解析成 {@link org.apache.http.client.methods.HttpPost} 对象
     *
     * @param URL     Http 请求地址
     * @param Headers Http 请求头
     * @return Post 请求
     */
    private HttpPost getPostConnection(String URL, List<Header> Headers) {
        HttpPost post = new HttpPost(URL);
        // 默认的请求头设置
        post.setHeader("User-Agent", "DimBottomRuntime/1.0.0");
        post.setHeader("Accept", "*/*");
        post.setHeader("Accept-Encoding", "gzip, deflate, br");
        post.setHeader("Connection", "keep-alive");
        // 加载外部传入的请求头
        if (Headers != null) {
            Headers.forEach(post::setHeader);
        }
        return post;
    }

    public String doPost(InfoParser.BasicInfo info) {
        return doPost(info.getUrl(), info.getHeaders(), info.getContent());
    }

    public String doPost(String URL) {
        return doPost(URL, null, null);
    }

    public String doPost(String URL, String content) {
        return doPost(URL, null, content);
    }

    /**
     * @param Url     Http 请求地址
     * @param Headers Http 请求头
     * @param content 请求的内容
     * @return 响应的内容，不包括响应头
     */
    public String doPost(String Url, List<Header> Headers, String content) {
        String res;
        try {
            client = HttpClients.createDefault();
            HttpPost post = getPostConnection(Url, Headers);
            if (content != null) {
                StringEntity se = new StringEntity(content);
                se.setContentType("application/json");
                post.setEntity(se);
            }
            CloseableHttpResponse response = client.execute(post);
            res = EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            res = null; // 内部错误
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return res;
    }

}